//
//  FDDTimer.m
//  FDDPlus
//
//  Created by Fadada-Zhou on 2017/4/13.
//  Copyright © 2017年 fadada. All rights reserved.
//

#import "FDDTimer.h"


@interface FDDTimer()

@property (nonatomic, strong) NSTimer          *timer;
@property (nonatomic, strong) NSThread         *runTimerThread;
//@property (nonatomic, assign) NSInteger         secondsCountDown;

@end

@implementation FDDTimer

-(instancetype)initWithSecoundCount:(NSInteger)seconds type:(SmsKindType)type{
    self = [super init];
    if (self) {
        self.secondsCountDown = seconds;
        self.type = type;
    }
    
    return self;
}


-(void)startFDDTimer{
    NSThread *runTimerThread = [[NSThread alloc] initWithTarget:self
                                                       selector:@selector(initTimer)
                                                         object:nil];
    [runTimerThread start];
    
}

-(void)stopFDDTimer{
    [self stopTimer];
}


-(void) initTimer{
    
    _timer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:0] interval:1 target:self selector:@selector(calculateLeftTime) userInfo:nil repeats:true];
    WS(weakSelf);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (weakSelf.delegate) {
            [weakSelf.delegate willFDDTimerStart:self];
        }
    });
    
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    //打开下面一行，该线程的runloop就会运行起来，timer才会起作用
    [[NSRunLoop currentRunLoop] run];
    
    
}

- (void)calculateLeftTime {
    _secondsCountDown -= 1;
    
    WS(weakSelf);

    dispatch_async(dispatch_get_main_queue(), ^{
        if (weakSelf.delegate) {
            [weakSelf.delegate didFDDTimerStart:weakSelf seconds:weakSelf.secondsCountDown];
        }
    });
    
    if (_secondsCountDown == 0) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.delegate) {
                [weakSelf.delegate didFDDTimerStop:self];
            }
            [self stopTimer];
        });
    }
}

- (void)stopTimer {
    
    if (_timer) {
        
        [_timer invalidate];
        _timer = nil;
        _delegate = nil;
    }
}


@end
